package org.phoenix.mall.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.phoenix.mall.admin.common.pojo.vo.CategoryVO;
import org.phoenix.mall.admin.common.pojo.vo.UserVO;
import org.phoenix.mall.admin.common.utils.PagedGridResult;
import org.phoenix.mall.admin.mapper.UserMapper;
import org.phoenix.mall.admin.pojo.User;
import org.phoenix.mall.admin.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private UserMapper userMapper;

    @Override
    public UserVO createUser(User user) {
        userMapper.insert(user);
        UserVO userVO = new UserVO();
        userVO.setId(user.getId());
        userVO.setUsername(user.getUsername());
        userVO.setMobile(user.getMobile());
        userVO.setEmail(user.getEmail());
        userVO.setMgStatus(user.getStatus());

        return userVO;
    }

    @Override
    public PagedGridResult getUserListByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<UserVO> list = userMapper.queryUserListByPage();
        if (CollectionUtils.isEmpty(list)){
            page = page - 1;
            page = page < 1 ? 1 : page;

            PageHelper.startPage(page, pageSize);
            list = userMapper.queryUserListByPage();
        }

        return setterPagedGrid(list, page);
    }

    @Override
    public UserVO getUser(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public User getUserById(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public int editUser(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public int removeUser(Integer userId) {
        return userMapper.deleteByPrimaryKey(userId);
    }

    @Resource
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User getByUsername(String username) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("username",username);
        return userMapper.selectOneByExample(example);
    }

    private PagedGridResult setterPagedGrid(List<UserVO> list, Integer page) {
        PageInfo<UserVO> pageList = new PageInfo<>(list);
        PagedGridResult grid = new PagedGridResult();
        grid.setPage(page);
        grid.setRows(list);
        grid.setTotal(pageList.getPages());
        grid.setRecords(pageList.getTotal());
        return grid;
    }
}
